package cn.tedu.course.base.file;

import cn.tedu.course.base.response.JsonResult;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @BelongsProject: jsd2503-3-project1-ywk
 * @BelongsPackage: cn.tedu.ivos.base.file
 * @Author: yinwenkang
 * @CreateTime: 2025-06-13  16:44
 * @Description: TODO
 * @Version: 1.0
 */
@RestController
@Slf4j
@Tag(name = "图片上传模块")
@RequestMapping("v1/file")
public class UploadController {
    @Operation(summary = "图片上传功能")
    @ApiOperationSupport(order = 10)
    @PostMapping("upload")
    public JsonResult upload(MultipartFile file) throws IOException {
        log.debug("上传图片:file={}",file);
        //1.获取图片的原始文件名
        String fileName = file.getOriginalFilename();//mwzz.png
        //2.截取图片的后缀名
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        //3.起一个不重复的新文件名
        fileName = UUID.randomUUID()+suffix;
        //4.指定图片存储路径
        String dirPath = "d:/zhclimg";
        //5.为了提高检索性能,我们可以设置一个日期路径作为图片存储的文件夹
        SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");
        //6.将当前时间转为上述格式
        String datePath = sdf.format(new Date());
        //7.将上面的图片存储路径与日期路径封装,创建File类对象
        File dirFile = new File(dirPath+datePath);
        //8.判断该文件夹是否存在
        if(!dirFile.exists()){
            dirFile.mkdirs();
        }
        //9.拼接一个完整的图片存储路径
        String filePath = dirPath+datePath+fileName;
        //10.将用户上传的图片,存入指定的文件夹中
        file.transferTo(new File(filePath));
        //11.将日期路径与图片名返回给前端
        return JsonResult.ok(datePath+fileName);
    }

    @Operation(summary = "图片删除功能")
    @ApiOperationSupport(order = 20)
    @PostMapping("remove")
    public JsonResult remove(String imgUrl){
        log.debug("删除图片:imgUrl={}",imgUrl);
        new File("d:/zhclimg"+imgUrl).delete();
        return JsonResult.ok();
    }

}
